﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Users
{


    public partial class UserManagement : BLL.WIN.Templates.DevxConfigurationUserControlTemplate
    {
        public DAL.Database.LOGIN_USER SELECTED_LOGIN_USER
        { get; set; }

        public UserManagement()
        {
            InitializeComponent();
            
            try
            {
                PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLESLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_SYSTEM_ROLESLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_SYSTEM_ROLESLoadAllResult _sYSTEM_ROLE)
                {
                    CheckedListBoxItem listViewItem = new CheckedListBoxItem();
                    listViewItem.Value = _sYSTEM_ROLE.ROLE_ID.ToString();
                    listViewItem.Description = _sYSTEM_ROLE.ROLE_NAME;
                    lstViewUserRoles.Items.Add(listViewItem);
                }));
            }
            catch { }

            btnAddNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnAddNew_ItemClick);
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);
            btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnRefresh_ItemClick);
            btnDeleteItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnDeleteItem_ItemClick);
        }

        private void btnDeleteItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (SELECTED_LOGIN_USER != null)
            {
                if (XtraMessageBox.Show("Are you sure you want to delete the current user?", "Confirm delete", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2).Equals(DialogResult.Yes))
                {
                    try
                    {
                        PRO_DOCSDatabaseDataContext.proc_LOGIN_USERSDelete(SELECTED_LOGIN_USER.LOGIN_USER_ID);
                        gridView1.DeleteSelectedRows();
                    }
                    catch
                    {
                        XtraMessageBox.Show("The selected user cannot be deleted as it is already used in another transaction(s)", "Action denied", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            UserManagementLoad();
        }

        private void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            bool continue_saving = true;

            bool user_name_exist = PRO_DOCSDatabaseDataContext.CHECK_USER_NAME_EXISTANCE(SELECTED_LOGIN_USER.LOGIN_USER_ID, txtLoginUserName.Text).Count() > 0;
            bool user_email_exist = PRO_DOCSDatabaseDataContext.CHECK_USER_EMAIL_EXISTANCE(SELECTED_LOGIN_USER.LOGIN_USER_ID, txtEmployeeEmail.Text).Count() > 0;
            bool password_matches = txtLoginPassword.Text.Equals(txtConfirmPassword.Text);

            continue_saving = !user_name_exist && !user_email_exist && password_matches;

            if (continue_saving)
            {
                if (SELECTED_LOGIN_USER.LOGIN_USER_ID > 0)//already existed user
                {
                    PRO_DOCSDatabaseDataContext.proc_LOGIN_USERSUpdate
                        (SELECTED_LOGIN_USER.LOGIN_USER_ID,
                        txtEmployeeName.Text,
                        txtEmployeeEmail.Text,
                        txtLoginUserName.Text,
                        BLL.Utilities.TextEncryption.Encrypt(txtLoginPassword.Text),
                        chkIsActiveUser.Checked
                        );

                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcEmployeeActive, chkIsActiveUser.Checked.ToString().ToLower());
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcEmployeeEmail, txtEmployeeEmail.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcEmployeeFullName, txtEmployeeName.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcEmployeeUserName, txtLoginUserName.Text);

                    ADD_LOGIN_USER_ROLES();
                }
                else //insert a new user
                {
                    long? new_login_user = 0;

                    PRO_DOCSDatabaseDataContext.proc_LOGIN_USERSInsert
                        (ref new_login_user,
                        txtEmployeeName.Text,
                        txtEmployeeEmail.Text,
                        txtLoginUserName.Text,
                        BLL.Utilities.TextEncryption.Encrypt(txtLoginPassword.Text),
                        chkIsActiveUser.Checked);

                    SELECTED_LOGIN_USER = (from users in PRO_DOCSDatabaseDataContext.LOGIN_USERs
                                           where users.LOGIN_USER_ID.Equals(new_login_user.Value)
                                           select users).FirstOrDefault();


                    ADD_LOGIN_USER_ROLES();
                    UserManagementLoad();
                }
            }
            else
            {
                if (user_email_exist)
                {
                    dxErrorProvider1.SetError(txtEmployeeEmail, BLL.WIN.Properties.ErrorProviderMessages.Default.InputDataAlreadyExists.Replace("{name}", txtEmployeeEmail.Text));
                }
                if (user_name_exist)
                {
                    dxErrorProvider1.SetError(txtLoginUserName, BLL.WIN.Properties.ErrorProviderMessages.Default.InputDataAlreadyExists.Replace("{name}", txtLoginUserName.Text));
                }
                if (!password_matches)
                {
                    dxErrorProvider1.SetError(txtConfirmPassword, BLL.WIN.Properties.ErrorProviderMessages.Default.ConfirmPasswordMatching);
                }
            }
        }

        private void ADD_LOGIN_USER_ROLES()
        {
            //1. delete old data
            PRO_DOCSDatabaseDataContext.proc_LOGIN_USER_ROLESDeleteByLOGIN_USER_ID
                (SELECTED_LOGIN_USER.LOGIN_USER_ID);

            for (int i = 0; i < lstViewUserRoles.Items.Count; i++)
            {
                if (lstViewUserRoles.GetItemChecked(i))
                {
                    PRO_DOCSDatabaseDataContext.proc_LOGIN_USER_ROLESInsert
                        (
                            SELECTED_LOGIN_USER.LOGIN_USER_ID,
                            Convert.ToInt64(lstViewUserRoles.GetDisplayItemValue(i).ToString())
                        );
                }
            }
        }

        private void btnAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SELECTED_LOGIN_USER = new DAL.Database.LOGIN_USER();

            txtEmployeeEmail.Text = string.Empty;
            txtEmployeeName.Text = string.Empty;
            txtLoginUserName.Text = string.Empty;
            txtLoginPassword.Text = string.Empty;
            txtConfirmPassword.Text = string.Empty;
            chkIsActiveUser.Checked = false;

            lstViewUserRoles.UnCheckAll();


            gridView1.UnselectRow(gridView1.FocusedRowHandle);
            gridView1.ClearSelection();
        }

        private void LOAD_LOGIN_USER_ROLES()
        {
            Dictionary<long, PRO_DOCS.DAL.Database.proc_LOGIN_USER_ROLESLoadAllByLOGIN_USER_IDResult> lOGIN_USER_ROLES = PRO_DOCSDatabaseDataContext.proc_LOGIN_USER_ROLESLoadAllByLOGIN_USER_ID(SELECTED_LOGIN_USER.LOGIN_USER_ID).ToDictionary(k => k.ROLE_ID, v => v);

            for (int i = 0; i < lstViewUserRoles.Items.Count; i++)
            {
                bool item_checked = lOGIN_USER_ROLES.ContainsKey(Convert.ToInt64(lstViewUserRoles.GetDisplayItemValue(i).ToString()));
                lstViewUserRoles.SetItemChecked(i, item_checked);
            }
        }

        private void UserManagement_Load(object sender, EventArgs e)
        {
            UserManagementLoad();
        }

        private void UserManagementLoad()
        {
            List<DAL.Database.LOGIN_USER> lOGIN_USERS = PRO_DOCSDatabaseDataContext.LOGIN_USERs.ToList();

            List<UserManagemntList> LOGIN_USERS = new List<UserManagemntList>();

            for (int i = 0; i < lOGIN_USERS.Count; i++)
            {
                UserManagemntList sINGLE_LOGIN_USER = new UserManagemntList();

                sINGLE_LOGIN_USER.IsValid = lOGIN_USERS[i].IS_ACTIVE_USER.Value.ToString().ToLower();

                sINGLE_LOGIN_USER.LOGIN_USER = lOGIN_USERS[i];

                LOGIN_USERS.Add(sINGLE_LOGIN_USER);
            }

            lstViewUsers.DataSource = LOGIN_USERS;

            gridView1.SelectRow(0);


        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            dxErrorProvider1.ClearErrors();

            if (e.FocusedRowHandle > -1)
            {
                UserManagemntList cURRENT_SELECTED_USER = gridView1.GetFocusedRow() as UserManagemntList;

                SELECTED_LOGIN_USER = cURRENT_SELECTED_USER.LOGIN_USER;

                txtEmployeeEmail.Text = SELECTED_LOGIN_USER.EMPLOYEE_EMAIL;
                txtEmployeeName.Text = SELECTED_LOGIN_USER.EMPLOYEE_FULL_NAME;
                txtLoginUserName.Text = SELECTED_LOGIN_USER.LOGIN_USER_NAME;
                txtLoginPassword.Text = BLL.Utilities.TextEncryption.Decrypt(SELECTED_LOGIN_USER.LOGIN_USER_PASSWORD);
                txtConfirmPassword.Text = BLL.Utilities.TextEncryption.Decrypt(SELECTED_LOGIN_USER.LOGIN_USER_PASSWORD);
                chkIsActiveUser.Checked = SELECTED_LOGIN_USER.IS_ACTIVE_USER.Value;


                LOAD_LOGIN_USER_ROLES();
            }
        }

        private void chkAllowExpiry_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAllowExpiry.Checked)
            {
                dtpkrExpiryDate.Enabled = false;
                dtpkrExpiryDate.EditValue = null;
            }
            else
            {
                dtpkrExpiryDate.Enabled = true;
                dtpkrExpiryDate.EditValue = DateTime.Now;
            }
        }
    }
}
